package io.github.weiranyi.listener;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.listener.adapter.AbstractAdaptableMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @Description
 * @Return
 * @Author https://weiranyi.github.io
 * @Date Created in 2022-12-20 19:48
 **/
@Component
// public class ConsumerListener implements MessageListener 没有Qos
public class ConsumerListener extends AbstractAdaptableMessageListener {
    // jackson提供序列化和反序列中使用最多的类，用来转换json的
    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        try {
            // 将message对象转为json
            JsonNode jsonNode = MAPPER.readTree(message.getBody());
            String name = jsonNode.get("name").asText();
            System.out.println(name);
            Thread.sleep(3000);
            System.out.println("3s后再接收消息");
            /**
             * basicAck(msgId,true);
             * msgId的位置: 投递这条消息唯一标识ID，此id是一个单调递增的正整数
             * true的位置：是否可以被批量处理以节约网络流量，若为true表示可以处理小于等于msgId的消息
             */
            // deliveryTag:表示消息投递序号
            long msgId = message.getMessageProperties().getDeliveryTag();
            channel.basicAck(msgId,true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
